package com.mentalhealthplatform.teacherV2.service;

import com.mentalhealthplatform.appModels.Tweet;
import com.mentalhealthplatform.global.elasticsearch.TweetElasticsearchV2;
import com.mentalhealthplatform.teacherV2.repository.TweetRepositoryV2;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TweetServiceV2 {
    private final TweetRepositoryV2 tweetRepositoryV2;
    private final TweetElasticsearchV2 tweetElasticsearchV2;

    //构造函数，初始化推文仓库和推文Elasticsearch实例
    public TweetServiceV2(TweetRepositoryV2 tweetRepositoryV2, TweetElasticsearchV2 tweetElasticsearchV2) {
        this.tweetRepositoryV2 = tweetRepositoryV2;
        this.tweetElasticsearchV2 = tweetElasticsearchV2;
    }

    // 保存推文并将其存储到Elasticsearch中
    public Tweet saveTweet(Tweet tweet) {
        tweetRepositoryV2.save(tweet);
        return tweetElasticsearchV2.save(tweet);
    }

    // 获取所有推文
    public List<Tweet> getAllTweets() {
        return tweetRepositoryV2.findAll();
    }

    // 获取所有草稿
    public List<Tweet> getDrafts() {
        return tweetRepositoryV2.findByStatus("draft");
    }

    // 获取所有回收站中的推文
    public List<Tweet> getTrash() {
        return tweetRepositoryV2.findByStatus("trash");
    }

    // 根据ID获取推文
    public Tweet getTweetById(Long id) {
        return tweetRepositoryV2.findById(id).orElse(null);
    }

    // 删除推文
    public void deleteTweet(Long id) {
        tweetRepositoryV2.deleteById(id);
        tweetElasticsearchV2.deleteById(id);
    }

    // 将推文移动到回收站
    public void moveToTrash(Long id) {
        Tweet tweet = tweetRepositoryV2.findById(id).orElseThrow(() -> new RuntimeException("Tweet not found"));
        tweet.setStatus("trash");
        tweetRepositoryV2.save(tweet);
    }
}